//
//  LBQRCodeViewController.m
//  Masonry
//
//  Created by luckyRoy on 2018/1/12.
//

#import "LBQRCodeViewController.h"

#define kScanRect CGRectMake(([UIScreen mainScreen].bounds.size.width-220)/2.0,100, 220, 220)

static CGFloat const LBQRCodeViewControllerLineHeight = 46;

@interface LBQRCodeViewController ()<AVCaptureMetadataOutputObjectsDelegate>{
    int num;
    NSTimer * timer;
    CAShapeLayer *cropLayer;
}
@property (strong,nonatomic)AVCaptureDevice * device;
@property (strong,nonatomic)AVCaptureDeviceInput * input;
@property (strong,nonatomic)AVCaptureMetadataOutput * output;
@property (strong,nonatomic)AVCaptureSession * session;
@property (strong,nonatomic)AVCaptureVideoPreviewLayer * preview;

@property (nonatomic, strong) UIImageView * line;
@property (nonatomic, strong) UILabel *declareLabel;

@property (nonatomic, assign) LBQRCodeViewDeclareType declareType;

@property (nonatomic, copy) LBQRCodeViewControllerBlock complete;

@end

@implementation LBQRCodeViewController

- (instancetype)initWithDeclareType:(LBQRCodeViewDeclareType)declareType
                           complete:(LBQRCodeViewControllerBlock)complete
{
    if (self = [super init]) {
        self.declareType = declareType;
        self.complete = complete;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"扫一扫上传文件";
    [self configView];
    
    self.view.backgroundColor = [UIColor blackColor];
}

-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self beginScanEven];
    
    [self beginScanUI];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [timer invalidate];
}

- (void)dealloc
{
    timer = nil;
}

- (void)beginScanEven
{
    [self setCropRect:kScanRect];
    
    [self performSelector:@selector(setupCamera) withObject:nil afterDelay:0.3];
}

- (void)beginScanUI
{
    num =0;
    timer = [NSTimer scheduledTimerWithTimeInterval:0.08 target:self selector:@selector(upToDownAnimation) userInfo:nil repeats:YES];
}

-(void)configView{
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:kScanRect];
    imageView.image = [UIImage imageNamed:@"lb_QRcode_circle"];
    [imageView.layer setMasksToBounds:YES];
    [self.view addSubview:imageView];
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,CGRectGetWidth(kScanRect), LBQRCodeViewControllerLineHeight)];
    _line.image = [UIImage imageNamed:@"lb_QRcode_line"];
    [imageView addSubview:_line];
}

-(void)upToDownAnimation
{
    num ++;
    CGRect newRect = self.line.frame;
    newRect.origin.y += num;
    if (CGRectGetMaxY(newRect) >= [self maxYForLine]) {
        //当达到底部时候再返回顶部从新开始
        num = 0;
        newRect.origin.y = [self minYForLine];
    }
    self.line.frame = newRect;
}

- (void)setCropRect:(CGRect)cropRect{
    cropLayer = [[CAShapeLayer alloc] init];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, nil, cropRect);
    CGPathAddRect(path, nil, self.view.bounds);
    
    [cropLayer setFillRule:kCAFillRuleEvenOdd];
    [cropLayer setPath:path];
    [cropLayer setFillColor:[UIColor blackColor].CGColor];
    [cropLayer setOpacity:0.6];
    
    
    [cropLayer setNeedsDisplay];
    
    [self.view.layer addSublayer:cropLayer];
}

- (void)setupCamera
{
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device==nil) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"设备没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }]];
        [self presentViewController:alert animated:YES completion:nil];
        return;
    }
    // Device
    _device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    // Input
    _input = [AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    // Output
    _output = [[AVCaptureMetadataOutput alloc]init];
    [_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //设置扫描区域
    CGFloat screenWidth = [[UIScreen mainScreen] bounds].size.width;
    CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
    CGFloat top = CGRectGetMinY(kScanRect)/screenHeight;
    CGFloat left = CGRectGetMinX(kScanRect)/screenWidth;
    CGFloat width = CGRectGetWidth(kScanRect)/screenWidth;
    CGFloat height = CGRectGetWidth(kScanRect)/screenHeight;
    ///top 与 left 互换  width 与 height 互换
    [_output setRectOfInterest:CGRectMake(top,left, height, width)];
    
    // Session
    _session = [[AVCaptureSession alloc]init];
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([_session canAddInput:self.input])
    {
        [_session addInput:self.input];
    }
    
    if ([_session canAddOutput:self.output])
    {
        [_session addOutput:self.output];
    }
    
    // 条码类型 AVMetadataObjectTypeQRCode
    [_output setMetadataObjectTypes:[NSArray arrayWithObjects:AVMetadataObjectTypeQRCode, nil]];
    
    // Preview
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame =self.view.layer.bounds;
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    // Start
    [_session startRunning];
    
    [self.view addSubview:self.declareLabel];
}

#pragma mark - getter

- (UILabel *)declareLabel
{
    if (!_declareLabel) {
        _declareLabel = [[UILabel alloc]initWithFrame:CGRectMake(0,CGRectGetMaxY(kScanRect) + 100, [[UIScreen mainScreen] bounds].size.width, 100)];
        _declareLabel.textAlignment = NSTextAlignmentCenter;
        _declareLabel.textColor = [UIColor whiteColor];
        _declareLabel.font = [UIFont systemFontOfSize:16];
        _declareLabel.numberOfLines = 0;
        NSString *urlStr = @"sc.lianj.com";
        NSString *totalStr = [NSString stringWithFormat:@"PC端打开地址：%@\n\n扫描页面二维码，轻松上传文件",urlStr];
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]initWithString:totalStr];
        NSRange range = [totalStr rangeOfString:urlStr];
        if (urlStr.length && range.location != NSNotFound) {
            [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:65/255.0 green:169/255.0 blue:242/255.0 alpha:1] range:range];
        }
        [_declareLabel setAttributedText:attributedString];
    }
    return _declareLabel;
}

- (CGFloat)minYForLine
{
    return -LBQRCodeViewControllerLineHeight;
}

- (CGFloat)maxYForLine
{
    return CGRectGetWidth(kScanRect) + LBQRCodeViewControllerLineHeight;
}

#pragma mark AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    NSString *stringValue;
    
    if ([metadataObjects count] >0)
    {
        //停止扫描
        [_session stopRunning];
        [timer setFireDate:[NSDate distantFuture]];
        
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        NSLog(@"扫描结果：%@",stringValue);
        
        NSArray *arry = metadataObject.corners;
        for (id temp in arry) {
            NSLog(@"%@",temp);
        }
        
        NSMutableArray *resultViewController = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
        
        for (NSInteger index = 0; index < self.navigationController.viewControllers.count; index++) {
            UIViewController *viewController = self.navigationController.viewControllers[index];
            if ([viewController isKindOfClass:[self class]]) {
                [resultViewController removeObjectAtIndex:index];
            }
        }
        self.navigationController.viewControllers = resultViewController;
        
        if (self.complete) {
            self.complete(stringValue);
        }
        
//        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"扫描结果" message:stringValue preferredStyle:UIAlertControllerStyleAlert];
//        [alert addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            if (_session != nil && timer != nil) {
//                [_session startRunning];
//                [timer setFireDate:[NSDate date]];
//            }
//
//        }]];
//        [self presentViewController:alert animated:YES completion:nil];
        
    } else {
        NSLog(@"无扫描信息");
        return;
    }
    
}

@end
